package com.gzhryc.html;

import java.io.File;
import java.util.List;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.html.models.HtmlTemplate;
import com.gzhryc.html.models.HtmlTheme;

/**
 * 页面主题管理者
 * @author zhanghao
 *
 */
public class HtmlThemeManager implements IHtmlThemeService{
	
	static Logger log = Logger.getLogger(HtmlThemeManager.class);
	
	static HtmlThemeManager me;
	
	public static HtmlThemeManager self(){
		if(me == null) {
			me = new HtmlThemeManager();
		}
		return me;
	}
	
	IHtmlThemeService htmlThemeSer;

	public void intital(String path,IHtmlThemeService htmlThemeSer) {
		try {
			this.htmlThemeSer = htmlThemeSer;
			
			File rootFile = new File(path + "/views");
			if(rootFile.exists() && rootFile.isDirectory()) {
				File[] dirFiles = rootFile.listFiles();
				for(int i=0;i<dirFiles.length;i++) {
					File dirFile = dirFiles[i];
					if(dirFile.isDirectory()) {
						HtmlTheme htmlTheme = new HtmlTheme(dirFile.getName(),dirFile.getPath().replace("\\", "/"));
						File htmlDirFile = new File(dirFile.getPath()+"/html");
						if(htmlDirFile.exists() && htmlDirFile.isDirectory()) {
							addHtmlTemplate(htmlTheme,htmlDirFile);
						}
						htmlThemeSer.addHtmlTheme(htmlTheme);
					}
				}
			}
		} catch (Exception e) {
			log.error("初始化页面主题错误",e);
		}
	}
	
	private void addHtmlTemplate(HtmlTheme htmlTheme,File dirFile) {
		File[] files = dirFile.listFiles();
		for(int i=0;i<files.length;i++) {
			File file = files[i];
			if(file.isDirectory()) {
				addHtmlTemplate(htmlTheme,file);
			}else if(file.isFile() && file.getName().endsWith(".html")){
				String htmlPath = file.getPath().replace("\\", "/").replace(htmlTheme.getRealFilePath()+"/html", "");
				HtmlTemplate htmlThemplate = new HtmlTemplate();
				htmlThemplate.setHtmlPath(htmlPath);
				htmlThemplate.setRealFilePath(file.getPath());
				htmlTheme.getTemplates().put(htmlThemplate.getHtmlPath(), htmlThemplate);
			}
		}
	}

	@Override
	public void addHtmlTheme(HtmlTheme htmlTheme) {
		if(htmlThemeSer != null) {
			htmlThemeSer.addHtmlTheme(htmlTheme);
		}
	}

	@Override
	public void addHtmlTemplate(String code, HtmlTemplate template) {
		if(htmlThemeSer != null) {
			htmlThemeSer.addHtmlTemplate(code,template);
		}
	}

	@Override
	public List<String> findByHtmlThemeCodes() {
		if(htmlThemeSer != null) {
			return htmlThemeSer.findByHtmlThemeCodes();
		}
		return null;
	}

	@Override
	public HtmlTheme getByCode(String code) {
		if(htmlThemeSer != null) {
			return htmlThemeSer.getByCode(code);
		}
		return null;
	}

	@Override
	public List<HtmlTemplate> findHtmlTemplateByCode(String code) {
		if(htmlThemeSer != null) {
			return htmlThemeSer.findHtmlTemplateByCode(code);
		}
		return null;
	}
}
